package com.wlf.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * 处理 @ComponentScan、@Component注解
 */
public class ComponentScanPostProcessor implements BeanFactoryPostProcessor {



    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        //查找类上有没有对应的注解
        ComponentScan componentScan = AnnotationUtils.findAnnotation(Config.class, ComponentScan.class);
        try {
            if (componentScan != null){
                //componentScan.basePackages() 拿到ComponentScan注解中的包名
                for (String basePackage : componentScan.basePackages()) {
                    //将包名转换为项目目录 **代表子包
                    //com.wlf.spring -> classpath*:com/wlf/spring/**/*.class
                    String path = "classpath*:" + basePackage.replace(".","/") + "/**/*.class";
                    //通过路径获取class资源
                    Resource[] resources = new PathMatchingResourcePatternResolver().getResources(path);
                    //获取bean的名称
                    AnnotationBeanNameGenerator generator = new AnnotationBeanNameGenerator();
                    //读取类的原信息
                    CachingMetadataReaderFactory factory = new CachingMetadataReaderFactory();
                    for (Resource resource : resources) {
                        //类名，注解等信息都可以获取到
                        MetadataReader reader = factory.getMetadataReader(resource);
                        //得到类的元信息
                        ClassMetadata metadata = reader.getClassMetadata();
                        //获取类名
                        //metadata.getClassName();
                        //判断此类是否含有响应的注解
                        AnnotationMetadata annotationMetadata = reader.getAnnotationMetadata();
                        if (annotationMetadata.hasAnnotatedMethods(Component.class.getName()) ||
                                annotationMetadata.hasMetaAnnotation(Component.class.getName())){
                            AbstractBeanDefinition bd = BeanDefinitionBuilder.
                                    genericBeanDefinition(metadata.getClassName())
                                    .getBeanDefinition();
                            if(configurableListableBeanFactory instanceof DefaultListableBeanFactory){
                                DefaultListableBeanFactory beanFactory =  (DefaultListableBeanFactory)configurableListableBeanFactory;
                                String beanName = generator.generateBeanName(bd, beanFactory);
                                beanFactory.registerBeanDefinition(beanName,bd);
                            }
                        }
                    }

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
